package com.runa.monitor.platinterface.extend.httpSimilar.tyAI;


import com.alibaba.fastjson.JSON;
import com.runa.monitor.comm.dto.newComm.AsynResult;
import com.runa.monitor.comm.dto.newComm.PanelVO;
import com.runa.monitor.comm.entity.CommPanel;
import com.runa.monitor.platinterface.meter3_0.util.MySqlJdbcUtil;
import com.runa.monitor.platinterface.mqtt.MqttUtil;
import com.runa.monitor.platinterface.platService.RepositoryService;
import com.runa.protocol.util.UtilTime;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
@EnableScheduling
@Slf4j
@Order(999997)
public class PanelServer implements CommandLineRunner {

    @Value("${similarNB.TYAI-Panel.driver:com.mysql.cj.jdbc.Driver}")
    private String driverOfTY;
    @Value("${similarNB.TYAI-Panel.url:jdbc:mysql://10.30.3.17:19030/dianxin?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=Asia/Shanghai}")
    private String urlOfTY;
    @Value("${similarNB.TYAI-Panel.username:root}")
    private String usernameOfTY;
    @Value("${similarNB.TYAI-Panel.password:doris#2022}")
    private String passwordOfTY;

    @Value("${similarNB.TYAI-Panel.enable:true}")
//    @Value("${similarNB.TYAI-Panel.enable:true}")
    private Boolean enableOfBJJN;
    @Value("${similarNB.TYAI-Panel.period:10}")
    private Long periodOfBJJN;
    @Value("${similarNB.TYAI-Panel.model:TYAI-Panel}")
    private String panelModel;
    
    @Resource
    private RepositoryService repositoryService;

    private MySqlJdbcUtil mySqlJdbcUtil;

    private final ConcurrentHashMap<String, String> bJRLPanelConcurrentHashMap = new ConcurrentHashMap<>();

    @Override
    public void run(String... args) throws Exception {
        log.info("TYAI CommandLineRunner Running---" + "enableOfBJRL:" + enableOfBJJN);
        if (enableOfBJJN) {
            ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
            scheduledExecutorService.scheduleAtFixedRate(this::bjjnExecute, 0, periodOfBJJN, TimeUnit.MINUTES);
        }
    }

    private void bjjnExecute() {
        log.info("-------------http TYAI Scheduled 面板信息启动-------------");
        List<CommPanel> panelList = repositoryService.getListCommPanelByNodeModel(panelModel);
        log.info("-------------http TYAI Scheduled 面板信息size-------------" + panelList.size());
        if (!panelList.isEmpty()) {
            try {
                tyai(panelList);
            } catch (Exception e) {
                log.error("太原AI面板同步异常: ", e);
            }
        }
//        tyai(panelList);
    }

    @SneakyThrows
    private void tyai(List<CommPanel> panelList) {
        if (mySqlJdbcUtil == null) mySqlJdbcUtil = new MySqlJdbcUtil(driverOfTY, urlOfTY, usernameOfTY, passwordOfTY);
//        String sql = "SELECT temperaturepanel_id,plan_time,temperature,humidity FROM realtime_share_d_temperaturepanel";
        String sql = "SELECT \n" +
                "  r.temperaturepanel_id,\n" +
                "  r.plan_time,\n" +
                "  r.temperature,\n" +
                "  r.humidity\n" +
                "FROM \n" +
                "  realtime_share_d_temperaturepanel r\n" +
                "INNER JOIN (\n" +
                "  SELECT \n" +
                "    temperaturepanel_id, \n" +
                "    MAX(plan_time) AS max_plan_time\n" +
                "  FROM \n" +
                "    realtime_share_d_temperaturepanel\n" +
                "  GROUP BY \n" +
                "    temperaturepanel_id\n" +
                ") AS latest\n" +
                "ON \n" +
                "  r.temperaturepanel_id = latest.temperaturepanel_id\n" +
                "  AND r.plan_time = latest.max_plan_time;";
        log.info("Sql语句为：" + sql);
        ArrayList<HashMap<String, Object>> hashMapArrayList = mySqlJdbcUtil.query(sql);
        log.info("DataList为：" + JSON.toJSONString(hashMapArrayList));

        for (CommPanel commPanel : panelList) {
            for (HashMap<String, Object> map : hashMapArrayList) {
                if (map.get("temperaturepanel_id").toString().equalsIgnoreCase(commPanel.getSerial())){
//                    Date date = new Date(Long.valueOf(map.get("DNT").toString()));
                    String collectTime = map.get("plan_time").toString();
                    //计量上次的采集时间
                    if (bJRLPanelConcurrentHashMap.get(commPanel.getSerial()) != null
                            && bJRLPanelConcurrentHashMap.get(commPanel.getSerial()).equalsIgnoreCase(collectTime)) {
                        continue;
                    } else {
                        bJRLPanelConcurrentHashMap.put(commPanel.getSerial(), collectTime);
                    }
                    PanelVO panelVO = new PanelVO();
                    panelVO.setSerial(commPanel.getSerial());
                    panelVO.setReadTime(UtilTime.StringToDate(collectTime, "yyyy-MM-dd HH:mm:ss"));
                    if (map.get("temperature") != null) {
                        panelVO.setTemperature(Float.valueOf(map.get("temperature").toString()));
                    }
                    if (map.get("humidity") != null) {
                        panelVO.setHumidity(Float.valueOf(map.get("humidity").toString()));
                    }
                    AsynResult asynResult = new AsynResult();
                    asynResult.successSetting();
                    asynResult.setContent(Collections.singleton(panelVO));
                    asynResult.setIdentity(commPanel.getId());
                    MqttUtil.send(PanelVO.TOPIC, asynResult);
                    break;
                }
            }
        }
    }
}
